/**
 * Created by Lenovo4 on 2016/2/19.
 */
// ---------创建连接-----------
var socket, advance;
/**
 * 初始化连接
 * @param host
 */
function chat_init(host) {
    socket = io.connect(host);
}
/**
 * 高级消息
 * @param data
 */
var advancemsg = function (userdata,data) {
    var msg = data.msg;
    msg.cot = msg.content;
    msg.username = msg.name;
    var message = advance_li(msg);
    $("#advance_msg").append(message);
    $("#advance_msg_DIV").scrollTop(document.getElementById('advance_msg').offsetHeight);
};
/**
 * 普通消息
 * @param userName
 * @param data
 */
var commonmsg = function (data) {
    var msg = data.msg;
    msg.cot = msg.content;
    msg.username = msg.name;
    var message;
    if (data.username === window.userId) {
        message = msg_to_div(msg);
    } else {
        message = other_div(msg);
    }
    $('#liaotianlist').append(message);
    // 滚动条保持最下方
    $("#Y_PubMes_Div").scrollTop(document.getElementById('liaotianlist').offsetHeight);
};
var sysmsg = function (sysMsg, users, data) {
    data.cot = sysMsg;
    var message = weilcomeuser(data);
    $('#liaotianlist').append(message);
    $("#Y_PubMes_Div").scrollTop(document.getElementById('liaotianlist').offsetHeight);
};
var authError = function(msg,type,data){
    if (data.msg.userIds === window.userId) {
        alert("您没有权限")
    }
};
/**
 * 链接聊天服务器
 * @param roomId
 * @param userName
 */
function chat_connection(roomId, user) {
    // 加入房间
    socket.on('connect', function () {
        socket.emit("connectionConfig", roomId, function () {
            socket.emit('join', user);
        });
    });
    // 监听消息
    socket.on('msg', commonmsg);
    //监听高级消息
    socket.on('msg_advance', advancemsg);
    // 监听系统消息
    socket.on('sys', sysmsg);
    //监听权限接口
    socket.on("authError",authError);
}


/**
 * 发送消息
 * @param msg
 * @param username
 */
function sendMsg(data, type) {
    switch (type) {
        case "advance":
            socket.send(data);
            break;
        case "":
            socket.send(data);
            break;
    }
}

function msg_to_div(data) {
    var str = '<div class="chat" id="" style="clear: right;"><p style="float:right;">' + data.username + '<span>（' + data.fttime + '）</span></p>' +
        '<a href="javascript://" onclick="" style="background-color:#81511c; color:white; clear:right; float:right;"  power="1" rolestyle="User1" zberstyle="" roomrolestyle="RoomUser14" roomroletitle="嘉宾客户：可文字和语音发言">' + data.cot + '</a>' +
        '</div>';
    return str;
}

function other_div(data) {
    var str = '<div class="chat" id="" style="clear: right;"><p>' + data.username + '<span>（' + data.fttime + '）</span></p>' +
        '<a href="javascript://" onclick="" power="1" rolestyle="User1" zberstyle="" roomrolestyle="RoomUser14" roomroletitle="嘉宾客户：可文字和语音发言">' + data.cot + '</a>' +
        '</div>';
    return str;
}
function advance_li(data) {
    var str = '<li>' +
        '<span class="yuan">' + data.username + '</span>' +
        '<span class="han">喊话</span>' +
        '<span class="con">' + data.cot + '</span>' +
        '</li>';
    return str;
}

function weilcomeuser(data) {
    var str = '<div class="chat" id="" style="clear: right;text-align: center;">' +
        '<a href="javascript://" onclick="" power="1" rolestyle="User1" zberstyle="" roomrolestyle="RoomUser14" roomroletitle="嘉宾客户：可文字和语音发言">' + data.cot + '</a>' +
        '</div>';
    return str;
}

function show() {
    var mydate = new Date();
    var str = mydate.getHours() + ':';
    str += mydate.getMinutes() + ':';
    str += mydate.getSeconds();
    return str;
}

function addliaotian1() {
    var adminid = $('#adminid').val();
    var username = $("#username").val();
    var mid = $("#mid").val();
    var filter = /二逼|傻逼|qq|QQ|扣扣|口口|抠抠|江泽民|胡锦涛|习近平|习进平|席进平|温家宝|李克强|领导人|国家|政府|枪|迷药|小姐|混蛋|你妈|尼玛|草泥|草|操|CNM|NMB|GAN|gan|GAO|gao|加我|逼|B|b|吊|屌|屄|菊花|犯罪|奸|贱|干|日/g;
    var cot = $('#Y_iSend_Input').html();
    var cot1 = cot.replace(/<.*?>/ig, "");
    if (filter.test(cot1)) {
        cot = cot.replace(filter, '**');
    } else {
    }
    var v = cot;
    if (adminid == 16) {
        if (!v) {
            notice("内容不能为空");
            $("#Y_iSend_Input").focus();
            return false;
        }
        var tomid, tousername, siliao;
        $("#Y_iSend_Input").html("");
        return false;
    } else if (adminid == -1) {
        notice("您没有权限");
        return false;
    } else {
        if (!v) {
            notice("内容不能为空");
            $("#Y_iSend_Input").focus();
            return false;
        }
        var tomid, tousername, siliao;
        $.ajax({
            url: "action.php?type=addliaotian",
            type: "POST",
            data: {content: v, username: username, mid: mid, type: ""},
            dataType: "json",
            error: function () {
            },
            success: function (data) {//如果调用php成功
                $("#advance").val("");
                advance = $("#advance").val();
                data.type = advance;
                if (data.stues == 'success') {
                    $("#Y_iSend_Input").html("");
                    sendMsg({"username": window.userId, "msg": data},"");
                } else {
                    notice('对不起，您所在的用户组不允许发言');
                }
                //title提示!!! www.lizaonet.com
                var dqtitle = $("title").html();
                dqtitle = dqtitle.replace("【您有新消息】", "");
                $(document).attr("title", dqtitle);//修改title值
            }
        });
    }
}

function hanhua_liaotian() {
    var adminid = $('#adminid').val();
    var username = $("#username").val();
    var mid = $("#mid").val();
    var filter = /二逼|傻逼|qq|QQ|扣扣|口口|抠抠|江泽民|胡锦涛|习近平|习进平|席进平|温家宝|李克强|领导人|国家|政府|枪|迷药|小姐|混蛋|你妈|尼玛|草泥|草|操|CNM|NMB|GAN|gan|GAO|gao|加我|逼|B|b|吊|屌|屄|菊花|犯罪|奸|贱|干|日/g;
    var cot = $('#_SpeakText').val();
    var cot1 = cot.replace(/<.*?>/ig, "");
    if (filter.test(cot1)) {
        cot = cot.replace(filter, '**');
    } else {
    }
    var v = cot;
    if (cot.length > 40) {
        alert("字数太长，只能输入40个字符");
        return false;
    }
    if (adminid == 16) {
        if (!v) {
            notice("内容不能为空");
            $("#_SpeakText").focus();
            return false;
        }
        var tomid, tousername, siliao;
        $("#_SpeakText").html("");
        return false;
    } else if (adminid == -1) {
        notice("您没有权限");
        return false;
    } else {
        if (!v) {
            notice("内容不能为空");
            $("#_SpeakText").focus();
            return false;
        }
        var tomid, tousername, siliao;
        $.ajax({
            url: "action.php?type=addliaotian",
            type: "POST",
            data: {content: v, username: username, mid: mid, type: "advance"},
            dataType: "json",
            error: function () {
            },
            success: function (data) {//如果调用php成功
                data.type = "advance";
                $("#_SpeakText").val("");

                if (data.stues == 'success') {
                    $("#_SpeakText").html("");
                    sendMsg({"username": window.userId, "msg": data},"advance");
                } else {
                    notice('对不起，您所在的用户组不允许发言');
                }
                $("#advance").val("");
                //title提示!!! www.lizaonet.com
                var dqtitle = $("title").html();
                dqtitle = dqtitle.replace("【您有新消息】", "");
                $(document).attr("title", dqtitle);//修改title值
            }
        });
    }
}
function notice(msg) {
    alert(msg);
}

function hanhua() {
    $(".speak-tip").show();
    $("#advance").val("advance");
    $("#_SpeakText").focus();
}

function closedialog() {
    $(".speak-tip").hide();
    $("#_SpeakText").val("");
}

$(function () {
    chat_init("ws://120.24.6.169:2022");
    chat_connection(window.currentRoomId, {
        "userids": window.userId,
        "username": window.currentUserName,
        "vip": window.currentUserType
    });
});

function tuankuang(id) {

    $("div[name='shoujiruanjian']").hide();
    $("div[name='huiyinxize']").hide();
    $("div[name='huiyinyoushi']").hide();
    $("div[name='kechengbiao']").hide();
    $("div[name='caijignshuju']").hide();
    $("div[name='" + id + "']").show();
}